﻿using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Web;
using TemplateFoundation.Exceptions;

namespace TemplateFoundation.Handlers
{
    /// <summary>
    /// Used to serve a british flag icon, commonly used when a british flag should be used for the "en" language branch
    /// </summary>
    /// <example>
    /// Example in web.config to return a british flag when the american flag is requested
    /// <add name="britishFlagHandler" path="/App_Themes/Default/Images/flags/en.gif" verb="GET" type="TemplateFoundation.Handlers.BritishFlagIconHandler"/>
    /// </example>
    public class BritishFlagIconHandler : IHttpHandler
    {
        private byte[] _image;

        /// <summary>
        /// Initializes a new instance of the <see cref="BritishFlagIconHandler"/> class, used to serve a british flag for american english in the EPiServer UI
        /// </summary>
        public BritishFlagIconHandler()
        {
            var file = GetType().Assembly.GetManifestResourceStream("TemplateFoundation.Images.FlagIcons.en-GB.gif");
            if (file==null)
            {
                throw new TemplateFoundationException("Unable to located british flag icon");
            }

            var image = Image.FromStream(file);

            var stream = new MemoryStream();

            image.Save(stream, ImageFormat.Png);

            _image = stream.ToArray();

            // Clean up
            stream.Close();
            stream.Dispose();
            image.Dispose();
        }

        #region IHttpHandler Members

        /// <summary>
        /// Gets a value indicating whether another request can use the <see cref="T:System.Web.IHttpHandler"/> instance.
        /// </summary>
        /// <value></value>
        /// <returns>true if the <see cref="T:System.Web.IHttpHandler"/> instance is reusable; otherwise, false.
        /// </returns>
        public bool IsReusable
        {
            get { return true; }
        }

        /// <summary>
        /// Enables processing of HTTP Web requests by a custom HttpHandler that implements the <see cref="T:System.Web.IHttpHandler"/> interface.
        /// </summary>
        /// <param name="context">An <see cref="T:System.Web.HttpContext"/> object that provides references to the intrinsic server objects (for example, Request, Response, Session, and Server) used to service HTTP requests.</param>
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "image/gif";
            context.Response.BinaryWrite(_image);
            context.Response.End();
        }

        #endregion
    }
}
